package service

import (
	"singo/model"
	"singo/serializer"

	"github.com/segmentio/ksuid"
)

// OrganizationCreateService 管理新增小组的服务
type OrganizationCreateService struct {
	Name      string `form:"name" json:"name" binding:"required,min=1,max=30"`
	Intro     string `form:"intro" json:"intro"`
	Avatar    string `form:"avatar" json:"avatar"`
	Score     uint   `form:"score" json:"score"`
	Head      string `form:"head" json:"head" binding:"required"`
	ParentID  string `form:"parent_id" json:"parent_id" binding:"required"`
	CreatedBy string `form:"created_by" json:"created_by"`
}

// OrganizationCreate 新增组织
func (service *OrganizationCreateService) OrganizationCreate(userUID string) *serializer.Response {
	uid := ksuid.New()

	organization := model.Organization{
		UID:       uid.String(),
		Name:      service.Name,
		Intro:     service.Intro,
		Avatar:    service.Avatar,
		ParentID:  service.ParentID,
		Head:      service.Head,
		CreatedBy: userUID,
	}

	count := 0
	model.DB.Model(&model.Organization{}).Where("name = ?", service.Name).Count(&count)
	if count > 0 {
		return &serializer.Response{
			Status: 40001,
			Msg:    "组织名称被占用",
		}
	}

	// 创建组织
	if err := model.DB.Create(&organization).Error; err != nil {
		return &serializer.Response{
			Status: 50001,
			Msg:    "组织保存失败",
			Error:  err.Error(),
		}
	}

	return &serializer.Response{
		Msg:    "成功",
		Data:   true,
		Status: 0,
	}
}
